package com.dongdong.consumer;

import com.dongdong.controller.SendMessageController;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.util.List;

@Component
@RocketMQMessageListener(topic = "topic",consumerGroup = "dongdongshop-producer")
public class UserConsumer implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {
   @Autowired
   private SendMessageController sendMessageController;

    @Override
    public void onMessage(String s) {
        System.out.println(s);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently(){
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                //所有消息都存在List <MessageExt> list中
                MessageExt messageExt =list.get(0);
                //消息体内容
                String number =new String (messageExt.getBody());
                try {
                    sendMessageController.message(number);
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }

            }
        });
    }
}
